package cn.demoncat.util.web.aspect;

import cn.demoncat.util.lang.entity.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

/**
 * 异常处理
 *
 * 针对 @ExceptionHandler 未拦截的错误，如404、500等异常
 *
 * @author 延晓磊
 * @since 2021年10月18日
 */
@RestController
public class ErrorController implements org.springframework.boot.web.servlet.error.ErrorController {

    private static final Logger LOG = LoggerFactory.getLogger(ErrorController.class);

    /**
     * 处理错误消息
     *
     * @return
     */
    @RequestMapping("/error")
    @ResponseBody
    public Result handle(HttpServletRequest request) {
        String uri = (String) request.getAttribute("javax.servlet.error.request_uri");
        Integer status = (Integer)request.getAttribute("javax.servlet.error.status_code");
        if (status == 404) {
            LOG.warn("拦截错误请求：uri = {}, status = {}", uri, status);
            return Result.ILLEGAL;
        }else{
            Exception exception = (Exception) request.getAttribute("javax.servlet.error.exception");
            LOG.error("拦截错误请求：uri = {}, status = {}", uri, status, exception);
            return Result.FAIL;
        }
    }

    @Override
    public String getErrorPath() {
        return "/error";
    }
}